package org.baeta.client;

import org.jboss.resteasy.client.ClientRequest;
import org.jboss.resteasy.client.ClientExecutor;
import org.jboss.resteasy.client.core.executors.ApacheHttpClientExecutor;
import org.baeta.business.AppProperties;
import org.apache.commons.httpclient.ProxyHost;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Description
 *
 * @author <a href="mailto:rui.baeta@gmail.com">Rui Baeta</a>
 */
public abstract class AbstractClient
{
    private static final Log LOG = LogFactory.getLog(AbstractClient.class);

    protected ClientRequest buildRequest(String uri)
    {
        //proxy host:port
        Boolean proxyUse = Boolean.valueOf(AppProperties.getInstance().getProperty("proxy"));
        ProxyHost proxyHost = null;
        if (proxyUse)
        {
            proxyHost = new ProxyHost(
                    AppProperties.getInstance().getProperty("proxy.host"),
                    Integer.valueOf(AppProperties.getInstance().getProperty("proxy.port"))
            );
        }

        //proxy authentication
        Boolean proxyAuth = Boolean.valueOf(AppProperties.getInstance().getProperty("proxy.auth"));
        String encodedAuthString = null;
        if (proxyAuth)
        {
            String user = AppProperties.getInstance().getProperty("proxy.auth.username");
            String pass = AppProperties.getInstance().getProperty("proxy.auth.password");
            String authString = String.format("%s:%s", user, pass);
            encodedAuthString = String.format("Basic %s", new String(Base64.encodeBase64(authString.getBytes())));
            LOG.debug(String.format("Using encoded authentication: %s", encodedAuthString));
        }

        HttpClient httpClient = new HttpClient();
        if (proxyUse)
        {
            httpClient.getHostConfiguration().setProxyHost(proxyHost);
        }
        ClientExecutor executor = new ApacheHttpClientExecutor(httpClient);

        ClientRequest request = new ClientRequest(uri, executor);
        request.accept("application/json");
        if (proxyAuth)
        {
            request.header("Proxy-authorization", encodedAuthString);
        }
        return request;
    }
}
